<template>
  <div class="manager-form">
    <div class="form">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-position="left"
        label-width="100px"
      >
        <el-form-item :label="$t('settings.roleName')" prop="name">
          <el-input
            v-model="form.name"
            :maxlength="50"
            @blur="trim('name')"
            @mouseout.native="blurRule($event)"
          />
        </el-form-item>

        <el-form-item :label="$t('settings.authoritySelect')">
          <div class="depts-tree">
            <el-tree
              ref="rights"
              :data="patterns"
              :props="patternProps"
              node-key="id"
              show-checkbox
              :default-checked-keys="defaultCheckedKeys"
              :default-expanded-keys="extendKeys"
            />
          </div>
        </el-form-item>

        <el-form-item :label="$t('settings.description')">
          <el-input
            v-model="form.description"
            type="textarea"
            @blur="trim('description')"
            @mouseout.native="blurRule($event)"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('form')">{{
            $t('common.submit')
          }}</el-button>
          <el-button @click="goBack">{{ $t('common.back') }}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import * as settings from '@/api/settings';
import { authList } from '@/utils/routers';
import { trim } from '@/utils/index';

export default {
  name: 'ManageRoleForm',
  data() {
    return {
      form: {
        id: null,
        name: null,
        pattern: [],
        description: null,
      },
      rules: {
        name: [
          {
            required: true,
            message: this.$t('settings.inputName'),
            trigger: 'blur',
          },
        ],
      },
      patterns: [],
      patternProps: {
        label: 'label',
        children: 'children',
      },
      extendKeys: [1],
    };
  },
  computed: {
    /**
     * 获得默认权限展示项
     */
    defaultCheckedKeys: function() {
      if (this.form.pattern && typeof this.form.pattern === 'string') {
        return JSON.parse(this.form.pattern);
      }
      return this.form.pattern;
    },
  },
  created() {
    this.dataInit();
  },
  methods: {
    /**
     * 数据初始化
     */
    async dataInit() {
      // 获取权限数据
      this.loadNode();
      // 判断是新建还是编辑 根据 id
      const id = this.$route.query.id;
      if (id) {
        settings
          .getRoleById(id)
          .then(res => {
            this.form = res.data;
          })
          .catch(err => {
            console.log(err);
          });
      }
    },
    /**
     * 获取权限数据
     */
    loadNode() {
      this.patterns = authList;
    },
    /**
     * 保存管理员角色
     */
    submitForm(formName) {
      this.form.pattern = JSON.stringify(this.$refs['rights'].getCheckedKeys());
      this.$refs[formName].validate(valid => {
        if (valid) {
          settings.saveRole(this.form, this.form.id).then(result => {
            this.$message({
              message: this.$t('common.operateSuccess'),
              type: 'success',
            });
            this.formVisible = false;
            this.getRoleList();
          });
        } else {
          this.$message({
            message: this.$t('settings.formError'),
            type: 'error',
          });
        }
      });
    },
    /**
     * 返回管理员角色列表
     */
    goBack() {
      this.$router.go(-1);
    },
    /**
     * 去除两端空格处理
     * @param {String} name 输入框名称
     */
    trim(name) {
      this.form[name] = trim(this.form[name]);
    },
    /**
     * 失去焦点
     * @param {DOMEvent} event 当前输入框
     */
    blurRule(event) {
      // 输入框失去焦点操作
      event.target.blur();
    },
  },
};
</script>

<style lang="scss" scoped>
.manager-form {
  padding: 15px;
}
.depts-tree {
  display: inline-block;
  min-width: 200px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
</style>
